<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/store'
import { useDebounceFn } from '@vueuse/core'
import { showToast } from 'vant'
import { event } from 'vue-gtag'
import { useWaitUserLoadFn } from '@/hooks'

import { fetchWatchBonusTask, fetchClaimTaskReward } from '@/api/task.js'

import TaskCard from '@/components/taskCard/taskCard.vue'
import BiPopup from '@/components/biPopup/index.vue'

const userStore = useUserStore()
const router = useRouter()

const taskList = ref([])
async function handleGetTaskConfig() {
    try {
        const res = await fetchWatchBonusTask(userStore.uuid)
        taskList.value = res.data.data
    } catch (error) {
        console.error(error)
    }
}
useWaitUserLoadFn(handleGetTaskConfig)

const rewardPopup = ref(false)
function handleOpenRewardPopup() {
    rewardPopup.value = true
}
function handleCloseRewardPopup() {
    rewardPopup.value = false
}
const handelGetRewrad = useDebounceFn(async () => {
    try {
        await fetchClaimTaskReward({
            device: userStore.uuid,
            taskId: currentTask.value.taskId
        })
        showToast('Reward Claimed Successfully')
        handleGetTaskConfig() // 领取成功刷新任务列表
        handleCloseRewardPopup()
    } catch (error) {
        console.error(error)
    }
    event(handleParseTaskName(currentTask.value.watchType, currentTask.value.count), {
        userId: userStore.uuid
    })
}, 500)

function handleParseTaskName(type, count) {
    if (type == 3) {
        return `Watch ${count} episodes`
    }

    if (type == 4) {
        return `Unlock ${count} play${count > 1 ? 's' : ''}`
    }

    return ``
}

const RewardType = {
    1: 'coin',
    2: 'cash'
}
function rewardType(type) {
    return RewardType[type]
}

function taskStatus(task) {
    const completed = task.completed >= task.count
    const unfinish = task.finished == 0 // 未领奖
    const finished = task.finished == 1 // 已领奖
    if (completed && unfinish) {// 完成任务未领取奖励
        return 1
    }

    if (finished) {// 完成任务已领取奖励
        return 2
    }

    return 0 // 未完成任务
}

function finishCount(finishCount, totalCount) {
    return finishCount > totalCount ? totalCount : finishCount
}

const currentTask = ref({})
function handleTaskFn(task) {
    const status = taskStatus(task)
    if (status === 0) {
        android.jumpToVideo()
    }

    if (status === 1) {
        currentTask.value = task // 供奖励弹窗使用
        handleOpenRewardPopup()
    }
}

const popupProps = computed(() => {
    return {
        type: 'normal',
        buttonText: 'Get it',
        rewardsType: currentTask.value.currency == 1 ? 'coin' : 'cash',
        rewardsNum: currentTask.value.fixedValue
    }
})
</script>

<template>
    <div class="box">
        <div class="box-title">
            <span class="box-title-main">Episode Rewards</span>
        </div>
        <div class="box-content">
            <TaskCard v-for="task in taskList" :key="task.taskId"
                :name="handleParseTaskName(task.watchType, task.count)" :type="rewardType(task.currency)"
                :num="task.fixedValue" :hide-icon="false" :finish-count="finishCount(task.completed, task.count)"
                :total-count="task.count" :status="taskStatus(task)" @btn-click="handleTaskFn(task)" />
        </div>

        <BiPopup v-model:show="rewardPopup" v-bind="popupProps" @click="handelGetRewrad">
        </BiPopup>

    </div>
</template>

<style scoped lang="scss">
.box {
    @extend %box;

    &-title {
        @extend %box-title;

        &-main {
            @extend %box-title-main;
        }

        &-sub {
            @extend %box-title-sub;

            &-inset {
                color: var(--task-color);
            }
        }
    }

    &-content {
        @extend %box-content;
    }
}
</style>